package common.controller;


import implementor.PurchaseItemImpl;
import implementor.PurchaseOrderImpl;



import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Vector;

import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import model.Material;

import common.view.PurchaseOrderView;

import utility.AppUtilities;
import utility.Constants;
import utility.Validater;
import utility.ViewUtilities;
import dao.PurchaseItemDao;
import dao.PurchaseOrderDao;
import dbhandelling.Connections;

import dto.MaterialSpecification;
import dto.PurchaseItem;
import dto.PurchaseOrder;

public class PurchaseOrderController implements ActionListener{
	private PurchaseOrder model;
	private PurchaseOrderView view;
	 private MaterialAdderController controller;
	    private static int srNo=1;
	    private Vector<PurchaseItem>purchaseItems;
	    
		public PurchaseOrderController(PurchaseOrderView view,PurchaseOrder model
				) throws Exception {
			super();
			this.model = model;
			this.view = view;
			view.actionlisteneres(this);
			AppUtilities.fillProjectNameCombo(view.getCbProjectName());
			AppUtilities.fillEmployeeCombo(view.getCbCheckedBy());
			AppUtilities.fillEmployeeCombo(view.getCbPreparedBy());
			purchaseItems=new Vector<PurchaseItem>();
			controller=new MaterialAdderController(view.getmAdder(), null);
			view.getmAdder().getBtnAdd().addActionListener(this);
			
		}
		
		 public void addInTable() throws SQLException
			{
			   Material material = controller.getModel();
			   PurchaseItem i = new PurchaseItem();
			   i.setModelMaterial(material);
			   i.setmCode(material.getMCode());
			   i.setmSpecCode(material.getCurrentSpecs().getAutoSpecCode());
			   i.setmQuantity(Double.parseDouble(view.getmAdder().getTfAmount().getText().trim()));
			  // i.setmPrice(Double.parseDouble(view.getTfRate().getText().trim())); 
			  // i.setmDiscount(Double.parseDouble(view.getTfDiscount().getText().trim()));
			  
			//  double amt=i.getmQuantity()*i.getmPrice();
			  
			  //double discount=i.getmDiscount();
			  
			  //double totalamt=amt-(amt*i.getmDiscount()/100);
			  
			   DefaultTableModel dm=(DefaultTableModel) view.getTable().getModel();
			   Material tempm=i.getModelMaterial();
			   MaterialSpecification specs= i.getModelMaterial().getCurrentSpecs();
			   
			   dm.addRow(new Object[]{srNo++,tempm.getMname(),specs.getmSpecs(),tempm.getUnit(),800,
					                  70,1000});
			   
			   purchaseItems.add(i);
			}
		    
		    
		    
			
			/**
			 * Called when save button is called.Should save the data in Indent and Indent Item tabels
			 * @throws Exception 
			 */
			
			private  void reactToSave() throws Exception
			{
				
				Connection con =Connections.getMyConnection();
				try {
					con.setAutoCommit(false);
					int autoId= this.saveToPurchaseOrder();
					this.saveToPurchaseItems(autoId);
				} catch (Exception e) {
					con.rollback();
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				con.commit();
				con.setAutoCommit(true);
				
				
			}
			
			private int saveToPurchaseOrder() throws Exception
			{
				PurchaseOrderDao inDao=new PurchaseOrderImpl();
				model=new PurchaseOrder();
				
				model.setIdVendor(1);
				model.setOrderNumber(view.getTfOrderNo().getText().trim());
				model.setOrderDate(ViewUtilities.convert(view.getTfOrderDate().getText().trim()));
				model.setQuoteNumber(view.getTfQuotationNo().getText().trim());
				model.setQuoteDate(ViewUtilities.convert(view.getTfQuotationDate().getText().trim()));
				model.setIndentNumber(Integer.parseInt(view.getTfIndentNo().getText().trim()));
				model.setIndentDate(ViewUtilities.convert(view.getTfIndentDate().getText().trim()));
				model.setIdProject(AppUtilities.getProjectId(view.getCbProjectName().getSelectedItem().toString()));
				model.setIdCostCenter(0);
				model.setTaxNo(0);
				//+++++++++++++++++++++
				model.setImportance(view.getCbPriority().getSelectedItem().toString());
				model.setPaymentTerms(view.getTfPaymentTerms().getText().trim());
				model.setPaymentMode(view.getCbPaymentMode().getSelectedItem().toString());
				model.setinspection(view.getTfInspection().getText().trim());
				model.setContactPerson(view.getTfContactPerson().getText().trim());
				//++++++++++++++++++++++
			//	model.setContactPersonNumber(Double.parseDouble(view.getTfcontactPersonNo().getText().trim()));
				model.setContactPersonNumber(99931991531.0);
				model.setIdEmployeePreparedBy(AppUtilities.getGeneratedById(view.getCbPreparedBy().getSelectedItem().toString()));
				model.setIdEmployeecheckedBy(AppUtilities.getGeneratedById(view.getCbCheckedBy().getSelectedItem().toString()));
			
				model=new PurchaseOrder(0, "", model.getIdVendor(),model.getOrderNumber(),model.getOrderDate(),
						model.getQuoteNumber(),model.getQuoteDate(),model.getIndentNumber(),
						model.getIndentDate(),model.getIdProject(),model.getIdCostCenter(),model.getTaxNo(),
						model.getImportance(),model.getPaymentTerms(), model.getPaymentMode(), model.getinspection(),
						model.getContactPerson(),model.getContactPersonNumber(),model.getIdEmployeePreparedBy(),
						model.getIdEmployeecheckedBy(),Constants.ACTIVE);
				
				inDao.add(model);
				int autoId= inDao.getAutoId();
				
				return autoId;
				
			}
			
			
			private void saveToPurchaseItems(int autopurchseItemId) throws  Exception
			{
			   
				int i =0;
				for(;i<this.purchaseItems.size();i++)
					this.purchaseItems.get(i).setIdPurchaseOrder(autopurchseItemId);
				
				PurchaseItemDao pItemsDao = new PurchaseItemImpl();;
				for(i=0;i<purchaseItems.size();i++)
					pItemsDao.add(this.purchaseItems.get(i));
			   
			}
			
			private void delete(int row)
			{
				JTable table=view.getTable();
				DefaultTableModel dm = (DefaultTableModel) table.getModel();
				dm.removeRow(row);
				purchaseItems.remove(row);
			}
			
			
		
		

		@Override
		public void actionPerformed(ActionEvent e) {
			String k=(String) e.getActionCommand();
			if(k.equals("SAVE"))
			{
				try {
					Validater val = new Validater(view);
					String message = val.validateForEmpty();
					if(message.equals(""))
					{
					  reactToSave();
					JOptionPane.showMessageDialog(null,"Successfully Saved!");
					val.refresh();
					}
				
					else
						JOptionPane.showMessageDialog(null,message);
					
				} catch (Exception e1) {
					JOptionPane.showMessageDialog(null,"Failed To Save!");
					e1.printStackTrace();
				}
			}
			if(k.equals("quotationDate"))
			{
				ViewUtilities.makeDateComponent(view.getTfQuotationDate());
			}
			if(k.equals("orderDate"))
			{

				ViewUtilities.makeDateComponent(view.getTfOrderDate());	
			}
			if(k.equals("indentDate"))
			{

				ViewUtilities.makeDateComponent(view.getTfIndentDate());	
			}
			
			if(k.equals("mAdderAdd"))
			{
				controller.changeModel();
				try {
					this.addInTable();
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		}
			    
		

}
